package com.lkx.config;


import com.lkx.apsect.CloudLimitApsect;
import com.lkx.service.factory.CloudlimitFactory;
import com.lkx.service.strategy.CloudLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

@Configuration
@EnableConfigurationProperties(CloudCurrentLimitProperties.class)
// 只有在配置了限流的配置信息时，才进行加载
@ConditionalOnProperty(prefix = CloudCurrentLimitProperties.CLOUD_CURRENT_LIMIT_PREFIX,value = "type")
@Slf4j
public class CloudCurrentLimitAutoConfiguration {

    @Autowired
    private CloudCurrentLimitProperties properties;

    @Bean
    public CloudLimitService limitServiceTemplate(){
        log.info("======================>>>>>>>>>>检测到[{}]限流配置，开始加载限流配置...",properties.getType().getDesc());
        if (StringUtils.hasText(properties.getRecordLimitUrl())){
            log.info("======================>>>>>>>>>>检测到[{}]限流记录配置，请注意监控服务是否可用...",properties.getRecordLimitUrl());
        }
        return CloudlimitFactory.getCloudLimitType(properties.getType());
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * redis的lua脚本对象
     * @return lua脚本对象
     */
    @Bean
    public DefaultRedisScript<Long> redisScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("CloudLimit.lua")));
        redisScript.setResultType(Long.class);
        return redisScript;
    }

    @Bean
    public CloudLimitApsect cloudLimitApsect(){
        return new CloudLimitApsect();
    }
}
